#encoding:utf8 

# HOST = "{set u host here!}"
# _name = "{set u host loging name here!}"
# _pwd  = "{set u host's pwd here!}"

import paramiko
import os, sys, time, threading, string, logging 


def _log_noempty(strarr):
	if len(strarr) == 0:
		pass
	else:
		logging.info("CONSOLE-->%s)"%(strarr))

#svr connect
class RemoteCtrl():
	_ssh = None
	_ftp = None

	def __init__(self, host, loginname, pwd, keyfile=None):
		self.HOST = host 
		self._name = loginname 
		self._pwd  = pwd
		self._keyfile = keyfile

	def _crt_sftpcon(self):
		try:
			con = paramiko.SSHClient()
			con.set_missing_host_key_policy(paramiko.AutoAddPolicy())
			if self._keyfile:
				con.connect(self.HOST, "", "", key_filename=self._keyfile)
			else:
				con.connect(self.HOST,username=self._name, password=self._pwd)
			logging.info ("SSH connect to the host-->>(%s) successful!"%self.HOST)
			return con
		except:
			logging.error ("SSH connect to the host-->>(%s) failed!"%self.HOST)
		
	def shareSFtp(self):
		if self._ssh == None:
			self._ssh = self._crt_sftpcon()
		if self._ftp ==None:
			self._ftp = self._ssh.open_sftp()
		return self._ftp

	def shareSSH(self):
		if self._ssh == None:
			self._ssh = self._crt_sftpcon()
		return self._ssh

	def close(self):
		if self._ftp:
			self._ftp.close() 
			self._ftp = None
		if self._ssh:
			self._ssh.close() 
			self._ssh = None

		self.HOST = None
		self._name = None
		self._pwd  = None
		logging.info("Connect closed!")

	#上传文件
	def commit_file(self, localfile, netfile):
		logging.info("Upload the file from local <%s> to <%s>"%(localfile, netfile))
		self.shareSFtp().put(localfile, netfile)

	#执行远端命令
	def ssh_command(self, strcmd): 		
		stdin , stdout , stderr = self.shareSSH().exec_command(strcmd)
		_log_noempty (stdout.readlines())
		_log_noempty (stderr.readlines())

	#下载目标文件
	def chkout_file(self, netfile, localfile):		
		self.shareSFtp().get(netfile , localfile)

	#压缩目标目录
	def zip_tardir(self, netfile, netdir):		
		stdin , stdout , stderr = self.shareSSH().exec_command("zip -q -r %s %s" % (netdir, netfile))
		_log_noempty (stdout.readlines())
		_log_noempty (stderr.readlines())


#=======================================
# TEMPLATE

# cli = RemoteCtrl("118.192.159.32", "root" , "a7636615")
# cli.commit_file(os.getcwd() + os.sep + "lib" + os.sep + "xxtea.py", "/root/upload_tmp.py")
# cli.close()
#=======================================